<template>
  <div class="view-fill repair-settings-patroitem">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btn-list="fullInfo.btnList"
        @returnBack="returnBack"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="setRules()"
              :label-width="formInfo.labelWidth"
              @handleEvent="handleEventForm"
            >
              <template v-slot:form-referenceRangeStart>
                <el-input-number
                  v-model="formInfo.data.referenceRangeStart"
                  :max="999999999999999"
                  :precision="2"
                  controls-position="right"
                  :min="-999999999999999"
                ></el-input-number>
                -
                <el-input-number
                  v-model="formInfo.data.referenceRangeEnd"
                  :max="999999999999999"
                  :precision="2"
                  controls-position="right"
                  :min="-999999999999999"
                ></el-input-number>
              </template>

              <template
                v-if="formInfo.data.itemType == 3"
                v-slot:form-defaultValue
              >
                <el-input-number
                  v-model="formInfo.data.defaultValue"
                  :max="999999999999999"
                  :precision="2"
                  controls-position="right"
                  :min="-999999999999999"
                ></el-input-number>
              </template>
            </page-form>

            <div
              v-if="formInfo.data.itemType == 1 || formInfo.data.itemType == 2"
              class="patrol-table-wrap"
            >
              <el-form ref="tableForm" :model="tableInfo" style="width: 600px">
                <page-table
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :check-box="false"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                >
                  <template v-slot:col-itemDetailName="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}.itemDetailName`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                validator: validateName,
                                trigger: 'blur',
                              },
                            ]
                          : []
                      "
                    >
                      <el-input
                        v-model="scope.row.itemDetailName"
                        :maxlength="50"
                        @change="
                          changeName(`data.${scope.$index}.itemDetailName`)
                        "
                      ></el-input>
                    </el-form-item>
                  </template>
                  <template v-slot:col-checkedNormal="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}.checkedNormal`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                validator: validateNormal,
                                trigger: 'change',
                              },
                            ]
                          : []
                      "
                    >
                      <el-radio-group
                        v-model="scope.row.checkedNormal"
                        @change="
                          changeNormal(`data.${scope.$index}.checkedNormal`)
                        "
                      >
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
  </div>
</template>

<script setup name="licenseModify">
import {
  createPatrolItem,
  getPatrolItemById,
  updatePatrolItem,
} from '@/api/core'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'title', 'id', 'type'])

const validateName = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入名称'))
  } else {
    callback()
  }
}
const validateNormal = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入选择选中是否正常'))
  } else {
    callback()
  }
}

const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
// 表单相关
const formInfo = ref({
  ref: null,
  data: {
    itemType: '',
  },
  fieldList: [
    {
      label: '名称',
      value: 'itemName',
      type: 'input',
      maxlength: 32,
    },
    {
      label: '是否必填',
      value: 'isRequired',
      type: 'radio-model',
      code: 'yes_or_no',
    },
    {
      label: '分类',
      value: 'itemClassify',
      type: 'select-model',
      show: true,
      code: 'patrol_item_classify',
    },
    {
      label: '类型',
      value: 'itemType',
      type: 'select-model',
      show: true,
      code: 'patrol_item_type',
      event: 'itemType',
    },
    {
      label: '项目描述',
      value: 'description',
      type: 'textarea',
    },
    {
      label: '参考范围',
      value: 'referenceRangeStart',
      type: 'slot',
    },
    {
      label: '单位',
      value: 'unitName',
      type: 'input',
    },
    {
      label: '默认值',
      value: 'defaultValue',
      type: 'input',
    },
  ],
  choiceRules: {
    itemName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    itemClassify: [{ required: true, message: '请输入分类', trigger: 'blur' }],
    itemType: [{ required: true, message: '请输入类型', trigger: 'blur' }],
    description: [{ required: true, message: '项目描述', trigger: 'blur' }],
  },
  numberRules: {
    itemName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    itemClassify: [{ required: true, message: '请输入分类', trigger: 'blur' }],
    itemType: [{ required: true, message: '请输入类型', trigger: 'blur' }],
    unitName: [{ required: true, message: '请输入单位', trigger: 'blur' }],
    description: [
      { required: true, message: '请输入项目描述', trigger: 'blur' },
    ],
    referenceRangeStart: [
      { required: true, message: '请输入参考范围', trigger: 'blur' },
    ],
    referenceRangeEnd: [
      { required: true, message: '请输入参考范围', trigger: 'blur' },
    ],
  },
  textRules: {
    itemName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    itemClassify: [{ required: true, message: '请输入分类', trigger: 'blur' }],
    itemType: [{ required: true, message: '请输入类型', trigger: 'blur' }],
    description: [{ required: true, message: '项目描述', trigger: 'blur' }],
  },
  labelWidth: '120px',
})
// 相关列表
const tableInfo = ref({
  data: [{ itemDetailName: '', checkedNormal: '' }],
  fieldList: [
    { label: '名称', value: 'itemDetailName', type: 'slot' },
    { label: '选中是否正常', value: 'checkedNormal', type: 'slot' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '90',
    btList: [
      {
        label: '添加',
        event: add,
        show: true,
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
        ifRender: ifRenderValue,
      },
    ],
  },
})
const formRefs = ref([])

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

watch(
  () => formInfo.value.data.itemType,
  (val) => {
    setRules()
    showFieldListItem(val == 3, 'referenceRangeStart')
    showFieldListItem(val == 3, 'unitName')
    showFieldListItem(val == 3 || val == 4, 'defaultValue')
    if (val == 1 || val == 2) {
      formInfo.value.data['unitName'] = ''
      formInfo.value.data['defaultValue'] = ''
      formInfo.value.data['referenceRangeStart'] = 0
      formInfo.value.data['referenceRangeEnd'] = 0
      proxy.$nextTick(() => {
        formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
      })
    } else if (val == 4) {
      for (let item in formInfo.value.fieldList) {
        if (formInfo.value.fieldList[item].value === 'defaultValue') {
          formInfo.value.fieldList[item].type = 'input'
          break
        }
      }
      formInfo.value.data['unitName'] = ''
      formInfo.value.data['referenceRangeStart'] = 0
      formInfo.value.data['referenceRangeEnd'] = 0
      proxy.$nextTick(() => {
        formRefs.value = [formInfo.value.ref]
      })
    } else if (val == 3) {
      for (let item in formInfo.value.fieldList) {
        if (formInfo.value.fieldList[item].value === 'defaultValue') {
          formInfo.value.fieldList[item].type = 'slot'
          break
        }
      }
      proxy.$nextTick(() => {
        formRefs.value = [formInfo.value.ref]
      })
    } else {
      showFieldListItem(false, 'referenceRangeStart')
      showFieldListItem(false, 'unitName')
      showFieldListItem(false, 'defaultValue')
    }
  }
)

onMounted(() => {
  formRefs.value = [formInfo.value.ref]
  if (props.id) {
    getDetails()
  } else {
    showFieldListItem(false, 'referenceRangeStart')
    showFieldListItem(false, 'unitName')
    showFieldListItem(false, 'defaultValue')
  }
})

function handleEventForm(event, val) {
  if (event === 'itemType') {
    tableInfo.value.data = [{ itemDetailName: '', checkedNormal: '' }]
    if (val == 1 || val == 2) {
      proxy.$nextTick(() => {
        proxy.$refs.tableForm.clearValidate()
      })
    }
  }
}
function ifRenderValue() {
  return tableInfo.value.data.length > 1
}
function showFieldListItem(show, nameValue) {
  let fieldList = formInfo.value.fieldList
  fieldList.map((item) => {
    if (item.value === nameValue) {
      item.show = show
    }
  })
}
function setRules() {
  proxy.$nextTick(() => {
    formInfo.value.ref.clearValidate()
  })
  if (formInfo.value.data.itemType == 1 || formInfo.value.data.itemType == 2) {
    return formInfo.value.choiceRules
  } else if (formInfo.value.data.itemType == 3) {
    return formInfo.value.numberRules
  } else if (formInfo.value.data.itemType == 4) {
    return formInfo.value.textRules
  } else {
    return formInfo.value.choiceRules
  }
}
function save() {
  const _formInfo = formInfo.value
  proxy.$fn.checkForm(formRefs.value).then(() => {
    if (
      (_formInfo.data.referenceRangeStart == '' ||
        _formInfo.data.referenceRangeEnd == '' ||
        _formInfo.data.referenceRangeStart == undefined ||
        _formInfo.data.referenceRangeEnd == undefined) &&
      _formInfo.data.itemType === 3
    ) {
      proxy.$message({
        message: '请输入参考范围',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    if (
      _formInfo.data.referenceRangeStart &&
      _formInfo.data.referenceRangeEnd &&
      _formInfo.data.referenceRangeStart > _formInfo.data.referenceRangeEnd
    ) {
      proxy.$message({
        message: '参考范围结束范围需大于开始范围',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let api
    let params = _formInfo.data
    params.customOptionList = tableInfo.value.data
    const type = props.type
    if (type === 'create') {
      api = createPatrolItem
    } else if (type === 'update') {
      api = updatePatrolItem
    } else {
      return
    }
    api(params).then((res) => {
      if (res && res.success) {
        showDialog.value = false
        emits('returnBack', true)
      }
    })
  })
}
function returnBack() {
  emits('returnBack', true)
}
function getDetails() {
  getPatrolItemById(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      tableInfo.value.data = resp.data.customOptionList
    }
  })
}
function add(row, index) {
  //添加
  let _tableInfo = tableInfo.value
  _tableInfo.data.splice(index + 1, 0, {
    itemDetailName: '',
    checkedNormal: '',
  })
}
function remove(row) {
  //删除
  let _tableInfo = tableInfo.value
  _tableInfo.data = _tableInfo.data.filter((item) => item !== row)
}
function changeName(str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function changeNormal(str) {
  proxy.$refs.tableForm.clearValidate(str)
}
</script>

<style scoped lang="scss">
.flex {
  display: flex;
  flex: 1;
}
:deep(.patrol-table-wrap) {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.flex-select :deep(.el-input--small) .el-input__inner {
  height: 28px !important;
}
:deep(.el-form-item__content) {
  display: flex;
}
.repair-settings-patroitem {
  :deep(.el-input-number) {
    width: 120px;
  }
}
</style>
